<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-06-03 11:58:48
-->
<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="g_t('public.calendar')"
    width="80vw"
    style="max-width: 1000px"
    :before-close="handleClose"
  >
    <div class="calendar-container">
      <el-tabs v-model="tabValue" @tab-change="handleTabChange">
        <el-tab-pane name="1" :label="$t('public.calendar')">
          <el-row
            type="flex"
            justify="space-between"
            class="dialog-table-filter"
          >
            <div class="row-left">
              <el-date-picker
                v-model="searchTime"
                class="item"
                :type="dateType"
                :clearable="false"
                style="min-width: 150px; width: 150px"
                :disabled-date="disabledDate"
                @change="handleDateChange"
              />
              <el-button type="primary" @click="handleQuery">{{
                $t('public.search')
              }}</el-button>
            </div>
          </el-row>
          <div v-loading="viewLoading">
            <FullCalendar
              ref="fullCalendar"
              class="full-calendar-container"
              :options="calendarOptions"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane name="2" :label="$t('fleet.vehicle')">
          <el-row
            type="flex"
            justify="space-between"
            class="dialog-table-filter"
          >
            <div class="row-left">
              <!-- <el-date-picker
                v-model="vehicleSearchTime"
                class="item"
                :clearable="false"
                style="min-width: 150px; width: 150px"
                :disabled-date="disabledDate"
              /> -->
              <DateTimeRange
                v-model="vehicleSearchTime"
                class="item"
                type="daterange"
                :clearable="false"
                picker-type="2"
                :disabled-date="disabledDate"
              />
              <!-- <CascaderArea
                v-model="listParams.regionCode"
                class="item"
                style="min-width: 200px; width: 200px"
                :placeholder="$t('public.region')"
                :level="2"
                @change="handleRegionChange"
              />
              <TextInput
                v-model="listParams.seatCount"
                class="item"
                :placeholder="$t('fleet.loadCapacity')"
                :maxlength="4"
                verify-type="nzint"
                clearable
              /> -->
              <el-button type="primary" @click="handleVehicleQuery">{{
                $t('public.search')
              }}</el-button>
              <!-- <el-button plain @click="handleVehicleReset">{{
                $t('public.reset')
              }}</el-button> -->
            </div>
          </el-row>
          <div v-loading="viewLoading">
            <FullCalendar
              ref="vehicleFullCalendar"
              class="full-calendar-container"
              :options="vehicleCalendarOptions"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
      <div class="tab-btn">
        <el-button plain type="primary" @click="handleCreate">{{
          $t('public.createOrder')
        }}</el-button>
      </div>
    </div>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.close')
        }}</el-button>
      </div>
    </template>
    <!-- 新建/编辑 -->
    <AddOrEditDialog
      v-if="addOrEditVisible"
      v-model="addOrEditVisible"
      type="add"
      @update="handleUpdateQuery"
    />
  </BaseDialog>
</template>

<script setup>
import FullCalendar from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import timeGridPlugin from '@fullcalendar/timegrid'
import resourceTimelinePlugin from '@fullcalendar/resource-timeline'
import vehicle from '@/assets/vehicle.png'
import AddOrEditDialog from './AddOrEditDialog.vue'

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})

const tabValue = ref('1')
const searchTime = ref(g_dayjs().format('YYYY-MM-DD'))
const dateType = ref('day')
const timePeriod = computed(() => {
  const time = g_dayjs(searchTime.value || new Date())
  return [
    time.startOf(dateType.value).format('YYYY-MM-DD 00:00:00'),
    time.endOf(dateType.value).format('YYYY-MM-DD 23:59:59')
  ]
})
const viewLoading = ref(false)
const fullCalendar = ref(null)
const calendarOptions = ref({
  plugins: [
    dayGridPlugin,
    interactionPlugin,
    timeGridPlugin,
    resourceTimelinePlugin
  ],
  locale: 'zh-cn', // zh-cn en
  initialView: 'resourceTimelineDay',
  allDaySlot: false,
  // axisFormat: 'h(:mm)tt',
  headerToolbar: {
    // left: 'prev,next',
    left: '',
    center: 'title',
    // left: 'prev,next today',
    right: 'resourceTimelineDay,resourceTimelineWeek,dayGridMonth'
  },
  // headerToolbar: false,
  buttonText: {
    // today: '今天',
    day: '日',
    week: '周',
    month: '月'
    // prev: '上个月',
    // next: '下个月'
  },
  // 时间轴间距
  slotMinTime: '00:00:00', // 最小时间
  slotMaxTime: '24:00:00', // 最大时间
  // 单个时间的时间间隔
  slotDuration: '00:30:00',
  slotLabelContent: arg => {
    // console.log('arg', arg)
    if (arg.view.type === 'resourceTimelineWeek') {
      return (
        g_dayjs(arg.date).format('M/DD') +
        ' ' +
        g_options.getOptionText(
          g_options.dateDayOptions,
          g_dayjs(arg.date).day(),
          ''
        )
      )
    } else {
      return arg.text
    }
  },
  resourceAreaColumns: [
    {
      headerContent: g_t('fleet.orderCarInfo')
    }
  ],
  resourceAreaWidth: '150px',
  resources: [
    // {
    //   id: 'a',
    //   title: '山水国际<br>深圳市-深圳市'
    // }
  ],
  resourceLabelContent: arg => {
    return { html: arg.resource.title }
  },
  initialDate: searchTime.value, // 初始化日期
  events: [
    // {
    //   resourceId: 'a', // 事件的唯一标识符
    //   title: '标题bbb', // 事件的标题
    //   start: '2025-05-09 01:00:00', // 事件的开始时间（ISO 8601 格式）
    //   end: '2025-05-10 03:10:00' // 事件的结束时间（ISO 8601 格式）
    // }
  ],
  eventContent: arg => {
    return { html: arg.event.title }
  },
  // 设置可见的日期范围为昨天到今天
  // visibleRange: currentDate => {
  //   return {
  //     start: yesterday.toISOString().substring(0, 10), // 截取字符串以去除时间部分
  //     end: today.toISOString().substring(0, 10)
  //   }
  // },
  // visibleRange: {
  //   start: '2025-05-09',
  //   end: '2025-05-25'
  // },
  slotLabelFormat: {
    hour: 'numeric',
    minute: '2-digit',
    hour12: false
  },
  eventTimeFormat: {
    hour: 'numeric',
    minute: '2-digit',
    hour12: false
  },
  viewDidMount: arg => {
    console.log('viewDidMount', arg)
    // 确保DOM元素已渲染完毕
  },
  eventClick: events => {
    console.log('eventClick', events.event)
  },
  datesSet: info => {
    // console.log('datesSet', info)
    // 确保DOM元素已渲染完毕
    nextTick(() => {
      // 找到时间轴容器并滚动到最左边
      document.querySelectorAll('.fc-scroller').forEach(item => {
        item.scrollLeft = 0
        item.scrollTop = 0
      })
      dateType.value = {
        resourceTimelineDay: 'date',
        resourceTimelineWeek: 'week',
        dayGridMonth: 'month'
      }[info.view.type]
      console.log('timePeriod.value', timePeriod.value)
      if (info.view.type === 'resourceTimelineWeek') {
        fullCalendar.value?.getApi().setOption('slotDuration', '24:00:00')
      } else {
        fullCalendar.value?.getApi().setOption('slotDuration', '00:30:00')
      }
    })
  }
})
// const vehicleSearchTime = ref(g_dayjs().format('YYYY-MM-DD'))
// const listParams = ref({
//   regionCode: '',
//   seatCount: ''
// })
const vehicleSearchTime = ref([
  g_dayjs().format('YYYY-MM-DD 00:00:00'),
  g_dayjs().format('YYYY-MM-DD 23:59:59')
])
const vehicleFullCalendar = ref(null)
const vehicleCalendarOptions = ref({
  plugins: [resourceTimelinePlugin],
  locale: 'zh-cn', // zh-cn en
  initialView: 'resourceTimelineWeek',
  allDaySlot: false,
  headerToolbar: false,
  // 时间轴间距
  slotMinTime: '00:00:00', // 最小时间
  slotMaxTime: '24:00:00', // 最大时间
  // 单个时间的时间间隔
  slotDuration: '24:00:00',
  slotLabelContent: arg => {
    return (
      g_dayjs(arg.date).format('M/DD') +
      ' ' +
      g_options.getOptionText(
        g_options.dateDayOptions,
        g_dayjs(arg.date).day(),
        ''
      )
    )
  },
  views: {
    resourceTimelineWeek: {
      // buttonText: '天',
      type: 'resourceTimelineWeek',
      duration: { days: 1 } // 设置为一天的视图
    }
  },
  resourceAreaColumns: [
    {
      headerContent: g_t('fleet.vehicleInfo')
    }
  ],
  resourceAreaWidth: '15%',
  resources: [
    // {
    //   id: 'a',
    //   title: '粤B52462<br>',
    //   seatCount: 30
    // }
  ],
  resourceLabelContent: arg => {
    // 获取当前资源的数据
    // const resourceData = arg.resource.extendedProps

    return {
      html: `<img src="${vehicle}" style="width: 16px; height: 16px; vertical-align: middle; margin-right: 5px;"/>${arg.resource.title}`
      // html: `${
      //   arg.resource.title
      // }<br><img src="${vehicle}" style="width: 16px; height: 16px; vertical-align: middle; margin-right: 5px;"/>${
      //   resourceData.seatCount || 0
      // }`
    }
  },
  initialDate: searchTime.value, // 初始化日期
  events: [
    // {
    //   resourceId: 'a', // 事件的唯一标识符
    //   title: '标题bbb', // 事件的标题
    //   start: '2025-05-09 01:00:00', // 事件的开始时间（ISO 8601 格式）
    //   end: '2025-05-10 03:10:00' // 事件的结束时间（ISO 8601 格式）
    // }
  ],
  eventContent: arg => {
    return { html: arg.event.title }
  },
  slotLabelFormat: {
    hour: 'numeric',
    minute: '2-digit',
    hour12: false
  },
  eventTimeFormat: {
    hour: 'numeric',
    minute: '2-digit',
    hour12: false
  },
  viewDidMount: function (view) {
    console.log('viewDidMount-2', view)
    // 确保DOM元素已渲染完毕
  },
  eventClick: events => {
    console.log('eventClick', events.event)
  },
  datesSet: info => {
    // console.log('datesSet', info)
    // 确保DOM元素已渲染完毕
    nextTick(() => {
      // 找到时间轴容器并滚动到最左边
      document.querySelectorAll('.fc-scroller').forEach(item => {
        item.scrollLeft = 0
        item.scrollTop = 0
      })
    })
  }
})
const addOrEditVisible = ref(false)

watch(
  () => timePeriod.value,
  (nv, ov) => {
    getTableList()
  },
  {
    deep: true
  }
)

onMounted(() => {
  nextTick(() => {
    getVehicleTableList()
    fullCalendar.value?.getApi()?.updateSize()
  })
})

const getTableList = () => {
  viewLoading.value = true
  calendarOptions.value.resources = []
  calendarOptions.value.events = []
  g_api.fleet
    .apiOrderQueryVehicle({
      startTime: timePeriod.value[0],
      endTime: timePeriod.value[1]
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        calendarOptions.value.resources = data.map(item => {
          return {
            id: item.orderId,
            title: `${item.customer}<br>${item.trip}`
          }
        })
        calendarOptions.value.events = data.flatMap(item => {
          return (item.vehicleScheduleList || []).map(info => {
            return {
              className: 'custom-evnet-class',
              color: '#6fba2c', // Event的背景颜色
              resourceId: item.orderId,
              vehicleId: info.vehicleId,
              title: `
                ${item.customer}<br>${item.trip}<br>
                ${g_dayjs(info.startTime).format('HH:mm')}
                ~
                ${g_dayjs(info.endTime).format('HH:mm')}
                ${info.vehiclePlate ? '<br>' + info.vehiclePlate : ''}
              `,
              start: info.startTime,
              end: info.endTime
            }
          })
        })
        console.log(
          'calendarOptions.value.events',
          calendarOptions.value.events
        )
      }
    })
    .finally(_ => {
      viewLoading.value = false
    })
}

const getVehicleTableList = () => {
  viewLoading.value = true
  const calendarApi = vehicleFullCalendar.value?.getApi()
  calendarApi.gotoDate(vehicleSearchTime.value[0] || new Date())
  vehicleCalendarOptions.value.resources = []
  vehicleCalendarOptions.value.events = []
  g_api.fleet
    .apiScheduleQueryCalendarInfo({
      startTime: g_dayjs(vehicleSearchTime.value[0] || new Date()).format(
        'YYYY-MM-DD 00:00:00'
      ),
      endTime: g_dayjs(vehicleSearchTime.value[1] || new Date()).format(
        'YYYY-MM-DD 23:59:59'
      )
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        vehicleCalendarOptions.value.resources = data.map((item, i) => {
          return {
            id: i + '-' + item.vehiclePlate,
            title: item.vehiclePlate
            // seatCount: item.seatCount
          }
        })
        vehicleCalendarOptions.value.events = data.flatMap((item, i) => {
          return (item.scheduleList || []).map(info => {
            return {
              className: 'custom-evnet-class',
              color: '#6fba2c', // Event的背景颜色
              resourceId: i + '-' + item.vehiclePlate,
              orderId: info.orderId,
              title: `
                ${info.customer}<br>${item.trip || ''}
                ${g_dayjs(info.startTime).format('M-DD HH:mm')}
                ~
                ${g_dayjs(info.endTime).format('M-DD HH:mm')}
              `,
              start: info.startTime,
              end: info.endTime
            }
          })
        })
        const currentViews = calendarApi.getOption('views')
        currentViews.resourceTimelineWeek.duration = {
          days:
            g_dayjs(vehicleSearchTime.value[1]).diff(
              vehicleSearchTime.value[0],
              'day'
            ) + 1
        }
        // 使用 setOption 更新整个 views 配置
        calendarApi.setOption('views', currentViews)
        // 刷新视图以应用更改
        calendarApi.render() // 或者使用 calendarApi.updateSize() 根据需求
      }
    })
    .finally(_ => {
      viewLoading.value = false
    })
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleTabChange = _ => {
  nextTick(() => {
    fullCalendar.value?.getApi().updateSize()
    vehicleFullCalendar.value?.getApi().updateSize()
    document.querySelectorAll('.fc-scroller').forEach(item => {
      item.scrollLeft = 0
    })
  })
}

const disabledDate = time => {
  return false
}

const handleDateChange = e => {
  console.log('handleDateChange', e)
  fullCalendar.value?.getApi().gotoDate(searchTime.value || new Date())
}

const handleQuery = () => {
  getTableList()
}

const handleVehicleQuery = () => {
  getVehicleTableList()
}

// const handleVehicleReset = () => {
//   Object.assign(listParams.value, {
//     regionCode: '',
//     seatCount: ''
//   })
//   handleVehicleQuery()
// }

const handleCreate = _ => {
  addOrEditVisible.value = true
}

const handleUpdateQuery = _ => {
  getTableList()
  getVehicleTableList()
  emit('update')
}
</script>

<style scoped lang="scss">
.calendar-container {
  position: relative;
  .tab-btn {
    position: absolute;
    right: 0;
    top: 0;
    z-index: 10;
  }
}

.dialog-table-filter {
  margin-bottom: 0;
}
.full-calendar-container {
  height: calc(100vh - 100px - 66px - 87px);
  :deep(.fc-license-message) {
    display: none;
  }
  :deep(.fc-header-toolbar) {
    margin-bottom: 5px;
  }
  :deep(.fc-button-group) {
    border-radius: 5px;
    .fc-prev-button,
    .fc-next-button {
      background-color: var(--button-bg);
      color: var(--button-text-color);
      border-color: var(--button-border-color);
      box-shadow: none !important;
    }
    .fc-button:not(.fc-prev-button, .fc-next-button) {
      background-color: #fff;
      color: #333;
      border-color: #eee;
      box-shadow: none !important;
      &:not(:disabled):active {
        background-color: var(--button-bg);
        color: var(--button-text-color);
        border-color: var(--button-border-color);
      }
      &:not(:disabled):active:focus {
        box-shadow: none;
      }
      &.fc-button-active {
        background-color: var(--button-bg);
        color: var(--button-text-color);
      }
    }

    .fc-button:hover,
    .fc-button:hover {
      opacity: 0.6;
    }
  }
}
.form-dialog-footer {
  margin-top: 10px;
}
.calendar-container {
  :deep(.el-tabs) {
    --el-tabs-header-height: 38px;
    vertical-align: middle;
  }
}
</style>
